import pystray
from PIL import Image
from io import BytesIO
import base64
import re
from event import UiEvent
class Tray:
    def _base64_to_image(self,base64_str: str) -> Image.Image:
        base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
        byte_data = base64.b64decode(base64_data)
        image_data = BytesIO(byte_data)
        img = Image.open(image_data)
        return img
    def __init__(self,page,UiEvent:UiEvent):
        self.ui_event = UiEvent
        self.page = page
        iconb64=''''''
        tray_image = self._base64_to_image(iconb64)
        self.tray=pystray.Icon('SillyTavernLauncher',icon=tray_image)
        
        self.tray.menu=pystray.Menu(
            pystray.MenuItem('打开主窗口',self.open_app),
            pystray.MenuItem('启动酒馆',self.start_st),
            pystray.MenuItem('关闭酒馆',self.stop_st),
            pystray.MenuItem('重启酒馆',self.restart_st),
            pystray.MenuItem('退出启动器',self.exit_app),
                            )
        self.tray.run_detached()
    def open_app(self,icon,query):
        self.page.window.visible = True
        try:
            self.page.update()
        except RuntimeError as e:
            if "Event loop is closed" in str(e):
                # 如果事件循环已关闭，则不执行更新操作
                pass
            else:
                raise
    def exit_app(self,icon,query):
        # 确保在退出前停止所有运行的进程
        if self.ui_event.terminal.is_running:
            self.ui_event.terminal.stop_processes()
        self.ui_event.exit_app_with_tray(None)

    def restart_st(self, icon, query):
        self.ui_event.restart_sillytavern(None)
    def start_st(self, icon, query):
        self.ui_event.start_sillytavern(None)
    def stop_st(self, icon, query):
        self.ui_event.stop_sillytavern(None)